package one.stand.controller;


import cn.hutool.core.util.StrUtil;
import com.jmp.api.user.dto.ImAllRequest;
import com.jmp.api.user.dto.ImContactRequest;
import com.jmp.autocofiguration.web.interceptor.SecurityAuthCheck;
import com.jmp.base.MessageApi;
import com.jmp.base.dto.*;
import com.jmp.feign.ImFeign;
import com.jmp.feign.MessageFeign;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import one.stand.advice.ResultEnum;
import one.stand.dto.UserDto;
import one.stand.enums.LoginEnum;
import one.stand.mapper.SeeRecordPublicMapper;
import one.stand.model.BusinessCard;
import one.stand.model.ResultModel;
import one.stand.service.BusinessCardBaseService;
import one.stand.service.user.TokenService;
import one.stand.service.user.UserAdminService;
import one.stand.util.AssertUtil;
import one.stand.util.DateUtil;
import one.stand.util.RequestContext;
import one.stand.util.RequestContextHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Objects;

@RequestMapping("userApi/im")
@RestController
@Api("聊天")
public class ImController extends BaseController {

    @Autowired
    private ImFeign imFeign;
    @Autowired
    private MessageFeign messageFeign;

    @Autowired
    private BusinessCardBaseService businessCardBaseService;
    @Autowired
    private UserAdminService userAdminService;
    @Autowired
    private SeeRecordPublicMapper seeRecordPublicMapper;
    @Autowired
    private TokenService tokenService;

    @ApiOperation(value = "联系我")
    @PostMapping("/contact")
    @SecurityAuthCheck
    public ResultModel contact(@RequestAttribute ImContactRequest request) {
        final RequestContext.User optUser = RequestContextHolder.getRequestContext().getUser();
        UserDto user = userAdminService.get(optUser.getUserId());
        AssertUtil.nonNull(user.getPhone(), ResultEnum.FAIL_PHONE_NO);

        BusinessCard card = businessCardBaseService.getByUserId(request.getToId());
        if (Objects.nonNull(card) || tokenService.hasLoginStatus(request.getToId(), LoginEnum.CRM)) {
            MessagePushRequest pushRequest = MessagePushRequest.builder()
                    .type(MessagePushType.IM_CONTACT)
                    .toId(request.getToId())
                    .title(user.getName() + "正在通过花园购与您发起聊天，请尽快回复！")
                    .pageParams(new Object[]{optUser.getUserId(), user.getName()})
                    .build();
            messageFeign.push(pushRequest);
        } else {
            UserDto userModel = userAdminService.get(optUser.getUserId());
            String[] arr = {StrUtil.subSufByLength(userModel.getName(), 10), DateUtil.getDay(), "点击进入开始于客户聊天"};
            MessageWxSubscribeDto messageDto = MessageWxSubscribeDto.builder()
                    .type(MessageApi.MSG_UNREAD)
                    .toId(request.getToId())
                    .pageArr(new String[]{String.valueOf(optUser.getUserId())})
                    .dataArr(arr)
                    .build();
            messageFeign.wxSubscribe(messageDto);
        }

        return ResultModel.success();
    }

    @ApiOperation(value = "发送消息")
    @PostMapping("/send")
    @SecurityAuthCheck
    public ResultModel send(@RequestAttribute ImSendRequest request) {
        return imFeign.imSend(request);
    }

    @ApiOperation(value = "获取聊天列表")
    @PostMapping("/chat")
    @SecurityAuthCheck
    public ResultModel chat(@RequestAttribute ImRequest request) {
        return imFeign.imChat(request);
    }

    @ApiOperation(value = "获取聊天列表，分页")
    @PostMapping("/chat/page")
    @SecurityAuthCheck
    public ResultModel<ImChatPageResponse> chatPage(@RequestAttribute ImChatPageRequest request) {
        return imFeign.chatPage(request);
    }

    @ApiOperation(value = "获取聊天内容")
    @PostMapping("/chat/content")
    @SecurityAuthCheck
    public ResultModel imChatContent(@RequestAttribute ImRequest request) {
        return imFeign.imChatContent(request);
    }

    @ApiOperation(value = "群发")
    @PostMapping("/chat/all")
    @SecurityAuthCheck
    public ResultModel imChatContent(@RequestAttribute ImAllRequest request) {
        AssertUtil.nonNull(request.getSendId(), ResultEnum.PARAM_CHECK);
        BusinessCard businessCard = businessCardBaseService.getByUserId(request.getSendId());
        if (Objects.nonNull(request.getToId())) {
            ImSendRequest sendRequest = ImSendRequest.builder()
                    .id(request.getSendId())
                    .targetUserId(request.getToId())
                    .imType("txt")
                    .content("感谢今天参加新闻发布会，我是主讲人孔祥安，我的微信kxa999，有任何问题可以加我微信")
                    .companyKey("huayuan")
                    .build();
            imFeign.imSend(sendRequest);
        } else {
            List<Integer> toUserIds = seeRecordPublicMapper.selectByCardId(businessCard.getCardId());
            for (Integer toUserId : toUserIds) {
                ImSendRequest sendRequest = ImSendRequest.builder()
                        .id(request.getSendId())
                        .targetUserId(toUserId)
                        .imType("txt")
                        .content("感谢今天参加新闻发布会，我是主讲人孔祥安，我的微信kxa999，有任何问题可以加我微信")
                        .companyKey("huayuan")
                        .build();
                imFeign.imSend(sendRequest);
            }
        }
        return ResultModel.success();
    }
}
